/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */
package com.yami.shop.listener;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yami.shop.bean.enums.AuditStatus;
import com.yami.shop.bean.enums.ShopStatus;
import com.yami.shop.bean.event.ShopApplyEvent;
import com.yami.shop.bean.model.ShopAuditing;
import com.yami.shop.bean.model.ShopDetail;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.service.ShopAuditingService;
import com.yami.shop.service.ShopDetailService;
import lombok.AllArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Objects;

/**
 * @Author lth
 * @Date 2021/8/4 9:27
 */
@Component("ShopApply")
@AllArgsConstructor
public class ShopApplyListener {

    private final ShopDetailService shopDetailService;
    private final ShopAuditingService shopAuditingService;

    @EventListener(ShopApplyEvent.class)
    @Transactional(rollbackFor = Exception.class)
    public void apply(ShopApplyEvent event) {
        Long shopId = event.getShopId();
        Long employeeId = event.getEmployeeId();
        Date now = new Date();
        ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(shopId);
        if (Objects.equals(shopDetail.getShopStatus(), ShopStatus.OPEN_AWAIT_AUDIT.value())) {
            throw new YamiShopBindException("店铺审核中，请不要重复提交");
        }
        ShopAuditing oldAuditing = shopAuditingService.getOne(Wrappers.lambdaQuery(ShopAuditing.class).eq(ShopAuditing::getShopId, shopId));
        ShopAuditing shopAuditing = new ShopAuditing();
        shopAuditing.setShopId(shopId);
        shopAuditing.setUserId(employeeId.toString());
        shopAuditing.setStatus(AuditStatus.WAITAUDIT.value());
        shopAuditing.setUpdateTime(now);
        if (Objects.nonNull(oldAuditing)) {
            shopAuditing.setShopAuditingId(oldAuditing.getShopAuditingId());
            shopAuditingService.updateById(shopAuditing);
        } else {
            shopAuditing.setCreateTime(now);
            shopAuditingService.save(shopAuditing);
        }
        // 更新店铺状态为开店待审核
        shopDetailService.updateStatus(shopId, ShopStatus.OPEN_AWAIT_AUDIT.value());
        // 更新状态后要清除缓存
        shopDetailService.removeShopDetailCacheByShopId(shopId);
    }
}
